import 'package:huxiaodui/api/api.dart';
import 'package:huxiaodui/components/button_item.dart';
import 'package:huxiaodui/view/pop_pages/unit_list_page.dart';
import 'package:huxiaodui/view/pop_pages/login_page.dart';
import 'package:huxiaodui/view/pop_pages/my_notice_page.dart';
import 'package:huxiaodui/view/pop_pages/my_units_page.dart';
import 'package:huxiaodui/utils/global_controller.dart';
import 'package:huxiaodui/view/pop_pages/alarm_list_page.dart';
import 'package:huxiaodui/view/pop_pages/my_info_page.dart';
import 'package:huxiaodui/view/pop_pages/set_page.dart';
import 'package:flutter/material.dart';
import 'package:huxiaodui/view/pop_pages/qr_scan_page.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

class SelfPage extends StatefulWidget {
  const SelfPage({super.key});

  @override
  SelfPageState createState() => SelfPageState();
}

class SelfPageState extends State<SelfPage> {
  addUnit() {
    /* 添加单位-菜单组件 */
    showMenu(
      context: context,
      /* 展示位置 */
      position: RelativeRect.fromLTRB(
          0,
          // 系统状态栏高度 + appBar高度
          MediaQuery.of(context).padding.top + AppBar().preferredSize.height,
          -1,
          0),
      items: <PopupMenuEntry>[
        PopupMenuItem(
          onTap: () async {
            // 获取相关权限
            await Permission.camera.request();
            await Permission.photos.request();

            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => const QrScanPage()),
            );
          },
          child: const Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [Icon(Icons.qr_code), SizedBox(width: 10), Text('扫码添加')],
          ),
        ),
        PopupMenuItem(
          onTap: () async {
            var codeController = TextEditingController();
            await showDialog(
              context: context,
              builder: (context) => AlertDialog(
                title: const Text('添加单位'),
                content: TextField(
                  textInputAction: TextInputAction.next,
                  autofocus: true,
                  readOnly: false,
                  controller: codeController,
                  decoration: const InputDecoration(
                    prefixIcon: Icon(Icons.code),
                    hintText: "请输入单位编号",
                    labelText: "单位编号",
                  ),
                ),
                actions: [
                  TextButton(
                    child: const Text('取消'),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                  TextButton(
                    child: const Text('确定'),
                    onPressed: () async {
                      await Api.request(
                        url: UnitUrl.join,
                        data: {"code": codeController.text},
                        success: (res) {
                          Navigator.pop(context);
                        },
                        isToast: true,
                      );
                    },
                  ),
                ],
              ),
            );
          },
          child: const Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [Icon(Icons.code), SizedBox(width: 10), Text('编号添加')],
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    var user = Provider.of<GlobalController>(context).user;

    Widget selfBottom = InkWell(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => MyInfoPage()),
        );
      },
      child: Container(
        padding:
            const EdgeInsets.only(left: 30, right: 30, top: 20, bottom: 20),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                const SizedBox(
                  width: 60,
                  height: 60,
                  child: CircleAvatar(
                    radius: 50,
                    backgroundImage: AssetImage('assets/images/black_car.jpg'),
                  ),
                ),
                const SizedBox(width: 10),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Text(
                          "${user?.name}",
                          style: const TextStyle(
                            fontSize: 24,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(width: 10),
                        Visibility(
                          visible: user?.sex == "男",
                          child: const Icon(
                            Icons.man_2,
                            color: Colors.blue,
                          ),
                        ),
                        Visibility(
                          visible: user?.sex == "女",
                          child: const Icon(
                            Icons.woman_2,
                            color: Colors.red,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 1),
                    Text(
                      "${user?.account}",
                      style: TextStyle(
                          fontSize: 14,
                          color: Theme.of(context)
                              .textTheme
                              .bodyMedium!
                              .color!
                              .withAlpha(1000)),
                    ),
                  ],
                ),
              ],
            ),
            const Icon(
              Icons.arrow_forward,
            ),
          ],
        ),
      ),
    );

    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text("我的"),
            Row(
              children: [
                Visibility(
                  visible: user != null,
                  child: IconButton(
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => MyNoticePage()),
                      );
                    },
                    icon: const Icon(Icons.notifications_none),
                  ),
                ),
                Visibility(
                    visible: user != null,
                    child: IconButton(
                      onPressed: () {
                        addUnit();
                      },
                      icon: const Icon(Icons.add_circle_outline),
                    )),
              ],
            ),
          ],
        ),
      ),
      body: Center(
        child: ListView(
          children: [
            const SizedBox(height: 20),
            Visibility(
              visible: user != null,
              child: selfBottom,
            ),
            Visibility(
                visible: user == null,
                child: ButtonItem(
                    iconData: Icons.login,
                    title: "前往登录",
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => const LoginPage()),
                      );
                    })),
            Visibility(
              visible: user != null,
              child: ButtonItem(
                iconData: Icons.ad_units_sharp,
                title: "我的单位",
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const MyUnitsPage()),
                  );
                },
              ),
            ),
            Visibility(
                visible: user != null,
                child: ButtonItem(
                    iconData: Icons.alarm,
                    title: "警报列表",
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => const AlarmListPage()),
                      );
                    })),
            // Visibility(
            //   visible: user != null,
            //   child: ListButton(
            //       iconData: Icons.alarm_add,
            //       title: "我要报警",
            //       onTap: () {
            //         Navigator.push(
            //           context,
            //           MaterialPageRoute(
            //               builder: (context) => const AlarmPush()),
            //         );
            //       }),
            // ),
            Visibility(
              visible: user != null && user.root,
              child: ButtonItem(
                  iconData: Icons.clear_all_outlined,
                  title: "所有单位",
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => const UnitListPage()),
                    );
                  }),
            ),
            ButtonItem(
                iconData: Icons.settings,
                title: "设置",
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const SettingPage()),
                  );
                }),
            Visibility(
              visible: user != null,
              child: ButtonItem(
                iconData: Icons.logout,
                title: "退出登录",
                onTap: () async {
                  await showDialog(
                    context: context,
                    builder: (context) => AlertDialog(
                      title: const Text('退出登录'),
                      content: const Text("是否确定退出登录？"),
                      actions: [
                        TextButton(
                          child: const Text('取消'),
                          onPressed: () {
                            Navigator.pop(context);
                          },
                        ),
                        TextButton(
                          child: const Text('确定'),
                          onPressed: () async {
                            Api.mobileApp.logout().then(
                              (value) {
                                Navigator.pop(context);
                              },
                            );
                          },
                        ),
                      ],
                    ),
                  );
                },
              ),
            )
          ],
        ),
      ),
    );
  }
}
